package com.wsc.wisdomchina.ai.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.iflytek.cloud.SpeechError;

import com.samton.interfaces.IBenFileCallBack;
import com.samton.interfaces.IBenSpeakCallBack;
import com.samton.mainSDK.IBenChatSDK;
import com.samton.mainSDK.IBenSpeakingSDK;
import com.samton.model.Constants;
import com.samton.utils.MediaManager;
import com.samton.utils.ToastUtil;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.ai.MyConstant;
import com.wsc.wisdomchina.ai.WebViewActivity;
import com.wsc.wisdomchina.ai.model.IBenDemoBean;
import com.wsc.wisdomchina.ai.utils.SpannableStr;
import com.wsc.wisdomchina.ai.widget.ImageZoomPop;
import com.wsc.wisdomchina.ai.widget.MyDialog;

import java.io.File;
import java.util.List;


/**
 * 聊天适配器
 */
public class IBenDemoChatAdapter extends BaseAdapter implements IBenSpeakCallBack {

    /**
     * 上下文对象
     */
    private Context mContext;
    /**
     * 在线聊天数据源
     */
    private List<IBenDemoBean> mMessageList;
    /**
     * 跳转链接的头
     */
    private static String url = "";
    /**
     * 用来显示动画的ImageView
     */
    private ImageView mImageView;
    /**
     * 复用控件
     */
    private ViewHolder mViewHolder;
    /**
     * 刷新UI的Handler
     */
    private Handler handler = new Handler();
    /**
     * 是否正在播放
     */
    private boolean isPlay = false;
    /**
     * 等待 显示的弹窗
     */
    private Dialog myDialog = null;

    /**
     * 构造函数
     *
     * @param mContext     上下文对象
     * @param mMessageList 数据源
     */
    public IBenDemoChatAdapter(Context mContext, List<IBenDemoBean> mMessageList) {
        super();
        this.mContext = mContext;
        this.mMessageList = mMessageList;
        // 文字转语音SDK
        IBenSpeakingSDK.getInstance().init(mContext);
        IBenSpeakingSDK.getInstance().setCallBack(this);
        myDialog = MyDialog.getLoadDialog(mContext, "正在下载");
    }

    /**
     * 更新数据
     *
     * @param mMessageList
     */
    public void updateList(List<IBenDemoBean> mMessageList) {
        this.mMessageList = mMessageList;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (mMessageList != null && mMessageList.size() > 0) {
            return mMessageList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return mMessageList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final IBenDemoBean message = mMessageList.get(position);
        // 初始化界面
        //answerType  0：纯文本，1：富文本，2：图片，3：语音， 4：文件
        // type 返回类型 0:系统回复，1：客服回复，2：客户消息
        mViewHolder = new ViewHolder();
        // 小笨  消息回复(纯文本)
        if (message.getType() == MyConstant.TYPE_IBEN && message.getAnswerType() == MyConstant.MESSAGE_TYPE_TEXT) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_msg_receive, parent, false);
            // 文字显示
            mViewHolder.mTextView = (TextView) convertView.findViewById(R.id.mTextView);
            mViewHolder.mTextView.setMovementMethod(LinkMovementMethod.getInstance());
            // mViewHolder.mTextView.setAutoLinkMask(Linkify.ALL);
            mViewHolder.mTextView.setText(Html.fromHtml(message.getContent().trim()));
        }
        // 小笨  消息回复图片  小笨返回图片的消息类型 是  3
        else if (message.getType() == MyConstant.TYPE_IBEN && message.getAnswerType() == 3) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_image_receive, parent, false);
            mViewHolder.mRichImg = ((ImageView) convertView.findViewById(R.id.mImg));
            // 显示网络图片
            Glide.with(mContext).load(message.getContent()).placeholder(R.drawable.progress_round).into(mViewHolder.mRichImg);
            mViewHolder.mRichImg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ImageZoomPop pop = new ImageZoomPop(mContext, message.getContent());
                    pop.showPopWindow();
                }
            });
        }
        //客服回复纯文本
        else if (message.getType() == MyConstant.TYPE_KEFU && message.getAnswerType() == MyConstant.MESSAGE_TYPE_TEXT) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_msg_receive, parent, false);
            // 文字显示
            mViewHolder.mTextView = (TextView) convertView.findViewById(R.id.mTextView);
//            mViewHolder.mTextView.setText(message.getContent());
            if (TextUtils.isEmpty(message.getContent())) {
                message.setContent("");
            }
            SpannableStringBuilder builder = SpannableStr.transString(message.getContent(), mContext);
            if (builder == null) {
                mViewHolder.mTextView.setText(message.getContent());
            } else {
                mViewHolder.mTextView.setText(builder);
            }


        }
        // 系统消息回复(富文本)
        else if (message.getType() == MyConstant.TYPE_IBEN && message.getAnswerType() == MyConstant.MESSAGE_TYPE_RICHTEXT) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_msg_receive_rich, parent, false);
            mViewHolder.mRichTitle = (TextView) convertView.findViewById(R.id.richTitle);
            mViewHolder.mRichImg = (ImageView) convertView.findViewById(R.id.richImg);
            mViewHolder.mRichDesc = (TextView) convertView.findViewById(R.id.richDesc);
            // 富文本标题
            mViewHolder.mRichTitle.setText(message.getRichTitle());
            // 显示网络图片
            Glide.with(mContext).load(message.getRichImg()).into(mViewHolder.mRichImg);
            // 富文本描述摘要显示
            mViewHolder.mRichDesc.setText(message.getRichDesc());
            mViewHolder.mRichImg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra("url", message.getFilePathString());
                    mContext.startActivity(intent);
                }
            });
        }
        // 客户文字消息
        else if (message.getType() == MyConstant.TYPE_USER && message.getAnswerType() == MyConstant.MESSAGE_TYPE_TEXT) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_msg_send, parent, false);
            // 文字显示层
            mViewHolder.mTextLayout = (RelativeLayout) convertView.findViewById(R.id.mTextLayout);
            // 录音显示层
            mViewHolder.mRecordLayout = (FrameLayout) convertView.findViewById(R.id.mRecordLayout);
            // 录音时间
            mViewHolder.mRecordTime = (TextView) convertView.findViewById(R.id.mRecordTime);
            // 文字显示
            mViewHolder.mTextView = (TextView) convertView.findViewById(R.id.mTextView);
            mViewHolder.mTextLayout.setVisibility(View.VISIBLE);
            mViewHolder.mRecordLayout.setVisibility(View.GONE);
            mViewHolder.mRecordTime.setVisibility(View.GONE);

//            mViewHolder.mTextView.setText(message.getContent());
            if (TextUtils.isEmpty(message.getContent())) {
                message.setContent("");
            }
            SpannableStringBuilder builder = SpannableStr.transString(message.getContent(), mContext);
            if (builder == null) {
                mViewHolder.mTextView.setText(message.getContent());
            } else {
                mViewHolder.mTextView.setText(builder);
            }
        }

        // 客户语音消息
        else if (message.getType() == MyConstant.TYPE_USER && message.getAnswerType() == MyConstant.MESSAGE_TYPE_VOICE) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_msg_send, parent, false);
            // 文字显示层
            mViewHolder.mTextLayout = (RelativeLayout) convertView.findViewById(R.id.mTextLayout);
            // 录音显示层
            mViewHolder.mRecordLayout = (FrameLayout) convertView.findViewById(R.id.mRecordLayout);
            // 录音时间
            mViewHolder.mRecordTime = (TextView) convertView.findViewById(R.id.mRecordTime);
            mViewHolder.mRecordTime.setText((int) mMessageList.get(position).getTime() + "\'");
            mViewHolder.mTextLayout.setVisibility(View.GONE);
            mViewHolder.mRecordLayout.setVisibility(View.VISIBLE);
            mViewHolder.mRecordTime.setVisibility(View.VISIBLE);
            mViewHolder.mRecordLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    playSound(view, mMessageList.get(position).getFilePathString(), 1);
                }
            });
        }
//        // TODO 小笨 回复 语音
//        else if (message.getType() == MyConstant.TYPE_IBEN && message.getAnswerType() == MyConstant.MESSAGE_TYPE_VOICE) {
//            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_receive_voice, parent, false);
//            mViewHolder.mRecordLayout = ((FrameLayout) convertView.findViewById(R.id.mRecordLayout_voice));
//            mViewHolder.mRecordTime = (TextView) convertView.findViewById(R.id.mRecordTime);
//            mViewHolder.mRecordTime.setText((int)mMessageList.get(position).getTime() + "\'");
//            mViewHolder.mRecordLayout.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    if (!isPlay){
//                        isPlay = true;
//                        IBenSpeakingSDK.getInstance().startSpeaking(mMessageList.get(position).getContent());
//                    }else {
//                        isPlay = false;
//                        IBenSpeakingSDK.getInstance().stopSpeaking();
//                    }
//                }
//            });
//        }
        // 客服 回复 语音
        else if (message.getType() == MyConstant.TYPE_KEFU && message.getAnswerType() == MyConstant.MESSAGE_TYPE_VOICE) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_receive_voice, parent, false);
            mViewHolder.mRecordLayout = ((FrameLayout) convertView.findViewById(R.id.mRecordLayout_voice));
            mViewHolder.mRecordTime = (TextView) convertView.findViewById(R.id.mRecordTime);
            mViewHolder.mRecordTime.setText((int) mMessageList.get(position).getTime() + "\'");
            mViewHolder.mRecordLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    playSound(view, mMessageList.get(position).getFilePathString(), 2);
                }
            });
        } else if (message.getType() == MyConstant.TYPE_KEFU && message.getAnswerType() == MyConstant.MESSAGE_TYPE_IMAGE) {
            // 客服 回复图片
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_image_receive, parent, false);
            mViewHolder.mRichImg = ((ImageView) convertView.findViewById(R.id.mImg));
            // 显示网络图片
            Glide.with(mContext).load(message.getFilePathString()).placeholder(R.drawable.progress_round).into(mViewHolder.mRichImg);
            mViewHolder.mRichImg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ImageZoomPop pop = new ImageZoomPop(mContext, message.getFilePathString());
                    pop.showPopWindow();
                }
            });
        } else if (message.getType() == MyConstant.TYPE_USER && message.getAnswerType() == MyConstant.MESSAGE_TYPE_IMAGE) {
            //客户 发送图片
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_msg_sendfile, parent, false);
            mViewHolder.mRichImg = ((ImageView) convertView.findViewById(R.id.mImageView));
            Glide.with(mContext).load(message.getContent()).placeholder(R.drawable.progress_round).into(mViewHolder.mRichImg);
            mViewHolder.mRichImg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ImageZoomPop pop = new ImageZoomPop(mContext, message.getContent());
                    pop.showPopWindow();
                }
            });
        } else if (message.getType() == MyConstant.TYPE_KEFU && message.getAnswerType() == MyConstant.MESSAGE_TYPE_FILE) {
            final ViewHolder finalHolder = mViewHolder;
            final Handler handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    finalHolder.mItemFileName.setText(message.getContent());
                    finalHolder.mItemFileSize.setText(getFileLength((int) ((File) msg.obj).length()));
                    return false;
                }
            });
            // 客服回复 文件
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_receive_file, parent, false);
            IBenChatSDK.downLoadFile(message.getFilePathString(), message.getContent(), new IBenFileCallBack() {
                @Override
                public void onSuccess(File file) {
                    Message msg = handler.obtainMessage();
                    msg.what = 0;
                    msg.obj = file;
                    handler.sendMessage(msg);
                }

                @Override
                public void onFailed(String s) {
                }
            });
            // 文件图片显示
            finalHolder.mImageView = (ImageView) convertView.findViewById(R.id.mImageView);
            // 文件名字
            finalHolder.mItemFileName = (TextView) convertView.findViewById(R.id.itemFileName);
            finalHolder.mItemFileName.setText("加载中……");
            // 文件大小
            finalHolder.mItemFileSize = (TextView) convertView.findViewById(R.id.itemFileSize);
            finalHolder.mImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    openFile(new File(Constants.FILE_PATH + "/" + message.getContent()));
                }
            });
        }
        convertView.setTag(mViewHolder);
        return convertView;
    }

    @Override
    public void onSpeakBegin() {

    }

    @Override
    public void onCompleted(SpeechError speechError) {

    }
    private class ViewHolder {
        /**
         * 文字显示
         */
        private TextView mTextView;
        /**
         * 录音时间
         */
        private TextView mRecordTime;
        /**
         * 文字显示层
         */
        private RelativeLayout mTextLayout;
        /**
         * 图片显示层
         */
        private RelativeLayout mImageLayout;
        /**
         * 录音显示层
         */
        private FrameLayout mRecordLayout;
        /**
         * 富文本显示图片
         */
        private ImageView mRichImg;
        /**
         * 富文本标题
         */
        private TextView mRichTitle;
        /**
         * 富文本描述摘要
         */
        private TextView mRichDesc;
        /**
         * 文件图片
         */
        private ImageView mImageView;
        /**
         * 文件名
         */
        private TextView mItemFileName;
        /**
         * 文件大小
         */
        private TextView mItemFileSize;
    }

    /**
     * 播放音频文件
     *
     * @param view     控件
     * @param filePath 文件地址
     */
    int lasttype = -1;

    public void playSound(View view, String filePath, final int type) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println(">>>>>>>文件不存在");
        } else {
            System.out.println(">>>>>>>文件存在");
            // 播放动画
            if (mImageView != null) {// 让第二个播放的时候第一个停止播放
                if (lasttype == 1) {
                    mImageView.setBackgroundResource(R.mipmap.v_r_anim3);
                } else if (lasttype == 2) {
                    mImageView.setBackgroundResource(R.mipmap.v_l_anim3);
                }
                mImageView = null;
            }
            mImageView = (ImageView) view.findViewById(R.id.mImageView);
            if (type == 1) {
                mImageView.setBackgroundResource(R.drawable.play_r);
            } else {
                mImageView.setBackgroundResource(R.drawable.play_l);
            }

            AnimationDrawable drawable = (AnimationDrawable) mImageView.getBackground();
            drawable.start();

            // 播放音频
            MediaManager.playSound(filePath, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (type == 1) {

                                mImageView.setBackgroundResource(R.mipmap.adj);
                            } else {
                                mImageView.setBackgroundResource(R.mipmap.v_l_anim3);
                            }
                        }
                    });
                }
            });
            lasttype = type;
        }
    }

    /**
     * 打开文件
     *
     * @param file
     */
    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //获取文件file的MIME类型
        String type = getMIMEType(file);
        //设置intent的data和Type属性。
        intent.setDataAndType(Uri.fromFile(file), type);
        //跳转
        try {
            mContext.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast("没有可以打开文件的应用");
        }

    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param file
     */
    private String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
    /* 获取文件的后缀名*/
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "") return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private final String[][] MIME_MapTable = {
            //{后缀名，MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"},
            {"", "*/*"}
    };

    private String getFileLength(int length) {
        String fileLength;
        int M, KB;
        int B = length;
        if (length > 1024) {
            KB = length / 1024;
            if (KB > 1024) {
                M = KB / 1024;
                fileLength = M + "M";
            } else {
                fileLength = KB + "KB";
            }
        } else {
            fileLength = length + "B";
        }
        return fileLength;
    }
}
